package com.gin.no_gay_alliance.fragment.primsg;

import android.os.Bundle;
import android.os.Parcel;
import android.os.Parcelable;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.gin.nga.exception.NgaClientException;
import com.gin.nga.exception.NgaException;
import com.gin.nga.response.body.nuke.PmReplyBody;
import com.gin.nga.response.field.SimpleUserInfo;
import com.gin.nga.response.field.user.UserContext;
import com.gin.nga.response.field.user.UserInfoContext;
import com.gin.no_gay_alliance.adpter.pm.PriMsgReplyAdapter;
import com.gin.no_gay_alliance.app.MyApplication;
import com.gin.no_gay_alliance.callback.Callback;
import com.gin.no_gay_alliance.databinding.FragmentPriMsgPageBinding;
import com.gin.no_gay_alliance.databinding.MergeRefreshRecyclerViewBinding;
import com.gin.no_gay_alliance.exception.RequireParamException;
import com.gin.no_gay_alliance.fragment.base.BaseBindingFragment;
import com.gin.no_gay_alliance.utils.HandlerMessage;
import com.gin.no_gay_alliance.viewmodel.PriMsgReplyItem;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import okhttp3.Call;

/**
 * 一页私信回复
 *
 * @author : ginstone
 * @version : v1.0.0
 * @since : 2023/9/1 15:08
 **/

public class PriMsgPageFragment extends BaseBindingFragment<FragmentPriMsgPageBinding> implements Callback<PmReplyBody>, SwipeRefreshLayout.OnRefreshListener {
    private Args argument;
    private RecyclerView rv;
    private SwipeRefreshLayout srl;
    private PriMsgReplyAdapter adapter;

    @Override
    protected void onCreateView() {
        if (getArguments() != null) {
            argument = getArguments().getParcelable(Args.class.getName());
        } else {
            throw new RequireParamException();
        }
        MergeRefreshRecyclerViewBinding merge = MergeRefreshRecyclerViewBinding.bind(b.getRoot());
        rv = merge.recyclerView;
        srl = merge.swipeRefreshLayout;

        adapter = new PriMsgReplyAdapter(requireActivity(), new ArrayList<>());
        rv.setLayoutManager(new LinearLayoutManager(requireActivity(), LinearLayoutManager.VERTICAL, false));
        rv.setAdapter(adapter);
        srl.setOnRefreshListener(this);
        sendRequest();
    }


    /**
     * 请求成功回调
     *
     * @param data 数据
     */
    @Override
    public void onSuccess(PmReplyBody body) {
        PmReplyBody.Data data = body.getData();
        // 通知activity请求成功
        getParentHandler().sendMessage(getParentHandler().obtainMessage(HandlerMessage.UPDATE_PRI_REPLY_BODY, data));
        UserContext userContext = data.getUserContext();
        // 参与用户
        List<SimpleUserInfo> users = data.getUsers();
        // 私信回复
        List<PriMsgReplyItem> items = data.getData().values().stream().map(i -> {
            PriMsgReplyItem item = new PriMsgReplyItem(i);
            users.stream().filter(u -> item.userId.equals(u.getUserId())).findFirst().ifPresent(userInfo -> item.username = userInfo.getUsername());

            Object userInfo = userContext.getUserInfo(item.userId, null);
            if (userInfo instanceof UserInfoContext) {
                UserInfoContext info = (UserInfoContext) userInfo;
                item.avatar = info.getAvatar();
                item.username = info.getUserInfo().getUsername();
            }
            return item;
        }).collect(Collectors.toList());
        // 更新数据
        ui(() -> adapter.updateData(items));

        requestFinally();
    }


    /**
     * 请求失败回调(一般为网络访问错误)
     *
     * @param call call
     * @param e    错误
     */
    @Override
    public void onFailure(@NonNull Call call, @NonNull IOException e) {
        Callback.super.onFailure(call, e);
        requestFinally();
    }

    /**
     * 处理Nga异常
     *
     * @param e 异常
     */
    @Override
    public void handleException(NgaException e) {
        Callback.super.handleException(e);
        requestFinally();
        if (e instanceof NgaClientException) {
            getParentHandler().toast(((NgaClientException) e).getReason().get(0));
        }
    }

    /**
     * Called when a swipe gesture triggers a refresh.
     */
    @Override
    public void onRefresh() {
        sendRequest();
    }

    public void sendRequest() {
        srl.setRefreshing(true);
        MyApplication.app.managerFactory.getPriMsgManager().read(argument.id, argument.page, this);
    }

    private void requestFinally() {
        getParentHandler().post(() -> srl.setRefreshing(false));
    }

    public static PriMsgPageFragment newInstance(Args arguments) {
        PriMsgPageFragment fragment = new PriMsgPageFragment();
        Bundle bundle = new Bundle();
        bundle.putParcelable(Args.class.getName(), arguments);
        fragment.setArguments(bundle);
        return fragment;
    }

    public static class Args implements Parcelable {
        public static final Creator<Args> CREATOR = new Creator<Args>() {
            @Override
            public Args createFromParcel(Parcel in) {
                return new Args(in);
            }

            @Override
            public Args[] newArray(int size) {
                return new Args[size];
            }
        };
        /**
         * 私信id
         */
        public long id;
        /**
         * 页数
         */
        public int page;

        public Args(long id, int page) {
            this.id = id;
            this.page = page;
        }

        protected Args(Parcel in) {
            id = in.readLong();
            page = in.readInt();
        }

        @Override
        public int describeContents() {
            return 0;
        }

        @Override
        public void writeToParcel(Parcel dest, int flags) {
            dest.writeLong(id);
            dest.writeInt(page);
        }
    }
}